import React, { useState, useRef, useEffect } from 'react'
import './classinfo.css'
import { Select, Input, Button, Table, Form, Popconfirm, Typography, Modal, message } from 'antd';
import { SyncOutlined, FormOutlined, DownloadOutlined } from '@ant-design/icons';
import axios from '../../axios/request'
import {
    importsExcel, //导入
    exportExcel //导出
} from '../../untils'
import { set } from 'lodash';

const { Option } = Select;
const { Search, InputNumber } = Input;


// 数据
let originData = [];
const EditableContext = React.createContext(null);
// 删除
// const EditableRow = ({ index, ...props }) => {
//   const [form] = Form.useForm();
//   return (
//     <Form form={form} component={false}>
//       <EditableContext.Provider value={form}>
//         <tr {...props} />
//       </EditableContext.Provider>
//     </Form>
//   );
// };
// 编辑
const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
}) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{
                        margin: 0,
                    }}
                    rules={[
                        {
                            required: true,
                            message: `${title}不能为空！`,
                        },
                    ]}
                >
                    {inputNode}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};
// 批量修改表单组件
const onFinish = (values) => {
    console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
};
const BatchForm = (param) => {
    const [visible, setVisible] = React.useState(false);
    const [confirmLoading, setConfirmLoading] = React.useState(false);
    // const [modalText, setModalText] = React.useState('Content of the modal');
    const classInp = useRef();
    const careerInp = useRef();
    const showModal = () => {
        let newArr = JSON.parse(localStorage.getItem('stuSelArr')) || [];
        console.log(newArr);
        if (newArr && newArr.length !== 0) {
            setVisible(true);
        } else {
            message.info('请选中需要修改的人员');
        }
    };
    // 确认
    const handleOk = () => {
        let className = classInp.current.input.value;
        let careerName = careerInp.current.input.value;
        if (className !== '' && careerName !== '') {
            param.refreshData(['classes', 'career'], [className, careerName]);
            classInp.current.input.value = ''
            careerInp.current.input.value = ''
            setConfirmLoading(true);
            setTimeout(() => {
                setVisible(false);
                setConfirmLoading(false);
            }, 2000);
        } else {
            message.info('输入框不能为空！');
        }
    };
    // 取消
    const handleCancel = () => {
        // console.log('取消');
        setVisible(false);
    };
    return (
        <>
            <Button type="primary"
                onClick={showModal}
                style={{ marginRight: '10px' }}
                icon={<FormOutlined />}
            >
                选中的全部学员修改
            </Button>
            <Modal
                title="班级修改"
                visible={visible}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={handleCancel}
                okText="确认"
                cancelText="取消"
                destroyOnClose
            >
                <Form
                    name="batchForm"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item label="班级修改为：">
                        <Input placeholder="请输入班级名称" ref={classInp} allowClear />
                    </Form.Item>
                    <Form.Item label="项目经理修改为：">
                        <Input placeholder="请输入项目经理名称" ref={careerInp} allowClear />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

// 表格函数组件
const ClassInfo = () => {
    const [form] = Form.useForm();
    const [data, setData] = useState(originData);
    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record) => record.key === editingKey;

    const [optionArr, setOptionArr] = useState([])




    // 获取数据
    const getUserData = () => {
        axios({
            url: '/v1/student/getclassinfo',
            method: 'GET',
            headers: {
                'isLoading': true
            }
        }).then(({ data }) => {
            data.data.forEach(ele => {
                ele.key = ele.id
            })
            originData = data.data;
            localStorage.setItem('originDataClass', JSON.stringify(data.data))
            setData(data.data)

            let option = []
            originData.forEach((item) => {
                if (item.classes !== 'NC2021WEB2') {
                    option.push(item.classes)
                }
            })
            option = Array.from(new Set(option))
            setOptionArr(option)

        })
    }
    useEffect(() => {
        let allTodo = JSON.parse(localStorage.getItem('originDataClass')) || [];


        if (allTodo.length !== 0) {
            originData = allTodo;

            let ClassArr = JSON.parse(localStorage.getItem('originDataClass'))
            let option = []
            ClassArr.forEach((item) => {
                if (item.classes !== 'NC2021WEB2') {
                    option.push(item.classes)
                }
            })
            option = Array.from(new Set(option))
            setOptionArr(option)

            setData(originData)
        }
        else {

            getUserData()

        }
        handleChange('NC2021WEB2')
        return (
            localStorage.setItem('stuSelArr', JSON.stringify([]))
        )
    }, [])
    //  const [selectionType, setSelectionType] = useState('checkbox');
    // 搜索框value
    const searchInp = useRef();
    // 搜索
    const onSearch = value => {
        let seaData = originData.filter(item => {
            return item.name.indexOf(value) !== -1
        })

        searchInp.current.input.value = '';

        setData(seaData);
    };
    // 点击刷新
    const onRefresh = () => {
        window.location.reload();
    }
    const selectInp = useRef();
    // 班级选择
    const handleChange = (value) => {
        console.log(`selected ${value}`);
        let selData = originData.filter(item => item.classes === value)
        setData(selData);
    }
    // 删除事件
    const handleDelete = (key) => {
        let dataSource = [...data];
        dataSource = dataSource.filter((item) => item.key !== key);

        originData = originData.filter((item) => item.key !== key);

        localStorage.setItem('originDataClass', JSON.stringify(originData))


        setData(dataSource);
    };
    // 编辑
    const edit = (record) => {
        console.log(record);
        form.setFieldsValue({
            classes: '',
            ...record,
        });
        setEditingKey(record.key);
    };
    // 页数
    const cancel = () => {
        setEditingKey('');
    };
    // 保存
    const save = async (key) => {
        try {
            const row = await form.validateFields();
            // const newData = [...data];
            const newData = [...originData];
            const index = newData.findIndex((item) => key === item.key);
            console.log(row);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row });
                setData(newData);
                handleChange('NC2021WEB2')
                window.location.reload();
                // console.log(newData);
                localStorage.setItem('originDataClass', JSON.stringify(newData))
                setEditingKey('');
            } else {
                newData.push(row);
                setData(newData);
                handleChange('NC2021WEB2')
                // console.log(newData);
                localStorage.setItem('originDataClass', JSON.stringify(newData))
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };
    // 选择框
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            // console.log(selectedRowKeys, selectedRows);
            localStorage.setItem('stuSelArr', JSON.stringify(selectedRows))
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            // Column configuration not to be checked
            name: record.name,
        }),
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
        ],
    };
    // 更新数据
    const refreshData = (typeName, record) => {
        console.log(typeName, record);

        let selectedRows = JSON.parse(localStorage.getItem('stuSelArr'))

        let arr = JSON.parse(localStorage.getItem('originDataClass'))

        for (let ind = 0; ind < typeName.length; ind++) {
            selectedRows.forEach((item) => {
                item[typeName[ind]] = record[ind]
                arr.forEach((i, index) => {
                    if (i.key === item.key) {
                        arr.splice(index, 1)
                    }
                })
            })
        }
        let newArr = [...selectedRows, ...arr]
        newArr.sort((a, b) => {
            return a.key - b.key
        })


        localStorage.setItem('originDataClass', JSON.stringify(newArr))
        setData(newArr)
        window.location.reload()

    }

    const [header, ActioHeader] = useState([
        {
            title: '编号',
            key: 'key',
            className: 'text-monospace',
        }, {
            title: '姓名',
            key: 'name',
        }, {
            title: '中兴班级',
            key: 'classes',
        },
        {
            title: '项目经理',
            key: 'career',
        },
        {
            title: '性别',
            key: 'sex',
        },
        {
            title: '毕业学校',
            key: 'graduate',
        },
        {
            title: '专业',
            key: 'profession',
        },
        {
            title: '学历',
            key: 'education',
        },
        {
            title: '联系电话',
            key: 'phone',
        },
    ])



    // 行数据配置
    const columns = [
        {
            title: '序号',
            dataIndex: 'key',
            sorter: (a, b) => a.key - b.key,
            width: '8%',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '姓名',
            dataIndex: 'name',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '班级',
            dataIndex: 'classes',
            align: 'center',
            editable: true,
            ellipsis: true,
        },
        {
            title: '项目经理',
            dataIndex: 'career',
            align: 'center',
            ellipsis: true,
            editable: true,
        },
        {
            title: '性别',
            dataIndex: 'sex',
            align: 'center',
            width: '6%',
            ellipsis: true,
        },
        {
            title: '毕业学校',
            dataIndex: 'graduate',
            width: '12%',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '专业',
            dataIndex: 'profession',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '学历',
            dataIndex: 'education',
            align: 'center',
            width: '8%',
            ellipsis: true,
        },
        {
            title: '联系电话',
            dataIndex: 'phone',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '修改',
            key: 'revise',
            align: 'center',
            width: '8%',
            render: (_, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <Typography.Link
                            onClick={() => save(record.key)}
                            style={{
                                marginRight: 8,
                            }}
                        >
                            保存
                        </Typography.Link>
                        <Popconfirm title="确认取消吗?" onConfirm={cancel}>
                            <a>取消</a>
                        </Popconfirm>
                    </span>
                ) : (
                    <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                        编辑
                    </Typography.Link>
                );
            },
        },
        {
            title: '删除',
            key: 'delete',
            align: 'center',
            width: '8%',
            render: (_, record) =>
                originData.length >= 1 ? (
                    <Popconfirm title="您确认删除吗?" onConfirm={() => handleDelete(record.key)}>
                        <a>删除</a>
                    </Popconfirm>
                ) : null,
        },
    ];
    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record) => ({
                record,
                // inputType: col.dataIndex === 'age' ? 'number' : 'text',
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });
    return (
        <div>
            <div className='ClassInfo'>
                <div className='table_fun'>
                    <div className='class_sel'>
                        所属班级：
                        <Select defaultValue="NC2021WEB2" style={{ width: 135, marginRight: '10px' }} onChange={handleChange} ref={selectInp}>
                            <Option value="NC2021WEB2">NC2021WEB2</Option>
                            {
                                optionArr.map((item, index) => {
                                    return <Option key={index} value={item}>{item}</Option>
                                })
                            }
                        </Select>
                    </div>
                    <div className='class_inp'>
                        <span>学员姓名：</span>
                        <Search allowClear placeholder="请输入学员名称" onSearch={onSearch} enterButton
                            ref={searchInp}
                        />
                    </div>
                    <Button
                        type="primary"
                        icon={<SyncOutlined />}
                        style={{ marginRight: '10px' }}
                        onClick={onRefresh}
                    >
                        刷新
                    </Button>
                    <BatchForm refreshData={refreshData} />

                    {/* 导入导出 */}
                    <div className='class_sel' style={{ marginLeft: '0px' }}>
                        <Button type="primary" onClick={() => {
                            exportExcel(header, data, "学生信息.xlsx")
                        }} icon={<DownloadOutlined />}>导出文件</Button>
                    </div>

                    <div className='class_sel' style={{ marginLeft: '10px', position: 'relative', cursor: 'pointer' }}>
                        <Button type="primary" style={{ cursor: 'pointer' }}>导入文件</Button>
                        <input type="file" accept=".xls,.xlsx" style={{ position: 'absolute', left: '0px', width: '90px', height: '40px', opacity: '0', cursor: 'pointer' }} onChange={(e) => {
                            importsExcel(e).then(function (data) {
                                let newArr = []
                                data.forEach((item) => {
                                    newArr.push({
                                        key: item['序号（id）'],
                                        name: item['姓名（name）'],
                                        classes: item['中兴班级（ZTEClass）'],
                                        career: item['项目经理'],
                                        sex: item['性别（sex）'],
                                        graduate: item['毕业学校（Graduated_school）'],
                                        profession: item['专业'],
                                        education: item['学历(Education)'],
                                        phone: item['联系电话(telephone)']
                                    })
                                })
                                localStorage.setItem('originDataClass', JSON.stringify(newArr))
                                originData = newArr
                                setData(newArr)
                            }, function (data) {
                                console.log(data);
                            })
                        }} />
                    </div>

                </div>

                <div className='table_box'>
                    <Form form={form} component={false}>
                        <Table
                            components={{
                                body: {
                                    // row: EditableRow,
                                    cell: EditableCell,
                                },
                            }}
                            bordered
                            dataSource={data}
                            columns={mergedColumns}
                            rowClassName="editable-row"
                            pagination={{
                                onChange: cancel,
                            }}
                            rowSelection={rowSelection}
                            scroll={
                                {
                                    y: 540
                                }
                            }
                        />
                    </Form>
                </div>
            </div>
        </div>
    );
};

export default ClassInfo

